﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Hrm.Core;
using Hrm.EntityFramework;
using Hrm.Services;
using Hrm.Web.Framework;

namespace Hrm.Web.Areas.Permissions.Controllers
{
    [RoleAuthorize]
    public class PermissionsController : Controller
    {
        IPermissionService _permissionService;

        public PermissionsController(IPermissionService permissionService)
        {
            _permissionService = permissionService;
        }

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult PagePermission(PageRequest<PermissionDto> request)
        {
            var result= _permissionService.GetPageList(request);
            return Json(result);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Code,Name")] Permission permission)
        {
            if (ModelState.IsValid)
            {
                this._permissionService.Insert(permission);
                return RedirectToAction("Index");
            }

            return View(permission);
        }

        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Permission permission = this._permissionService.GetById(id);
            if (permission == null)
            {
                return HttpNotFound();
            }
            return View(permission);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Permission permission)
        {
            if (ModelState.IsValid)
            {
                var model = this._permissionService.GetById(permission.Id);
                if (TryUpdateModel(model, new string[] { "Code", "Name" }))
                {
                    this._permissionService.Update(model);
                    return RedirectToAction("Index");
                }
            }
            return View(permission);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {
            ResponseModel result = new ResponseModel();
            var model = this._permissionService.GetById(id);
            if (model == null)
            {
                result.SetFailed("删除失败：没有你要删除的数据！");
                return Json(result);
            }
            _permissionService.UpdateDisabled(model);
            return Json(result);
        }
    }
}
